package com.oocl.o2o.client.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import com.oocl.o2o.client.dao.CustomerDao;
import com.oocl.o2o.client.entity.Customer;

/**
 * @description: CustomerDaoImpl
 * @author  XIEMI2
 * @date Aug 12, 2017 3:26:28 PM
 * @version 1.0
 */
@Repository
public class CustomerDaoImpl implements CustomerDao{

	@PersistenceContext(name="un")
	private EntityManager em;
	
	@Override
	public List<Customer> findAll() {
		String jpql = "from Customer";
		List<Customer> customers = em.createQuery(jpql).getResultList();
		return customers;
	}

	@Override
	public Customer add(Customer customer) {
		em.persist(customer);
		return customer;
	}

	@Override
	public Customer delete(String customerId) {
		Customer customer = em.find(Customer.class, customerId);
		em.remove(customer);
		return customer;
	}

	@Override
	public Customer update(Customer customer) {
		em.find(Customer.class, customer.getId());
		em.clear();
		em.merge(customer);
		return null;
	}

	@Override
	public Customer findById(String customerId) {
		Customer customer = em.find(Customer.class, customerId);
		return customer;
	}

	@Override
	public Customer findByCustomerName(String customerName) {
		String jpqlString = "from Customer c where c.username =:customerName";
		List<Customer> customers = em.createQuery(jpqlString).setParameter("customerName", customerName).getResultList();
		if(customers.size() > 0){
			return customers.get(0);
		}
		return null;
	}

	@Override
	public Customer findByCustomerId(String customerId) {
		Customer customer = em.find(Customer.class, customerId);
		return customer;
	}

	@Override
	public Customer findByCustomerNameAndPassword(String merchantName, String password) {
		String jpql = "from Customer c where c.username =:merchantName and c.password =:password";
		List<Customer> customers = em.createQuery(jpql).setParameter("merchantName", merchantName).setParameter("password", password).getResultList();
		if(customers.size() > 0){
			return customers.get(0);
		}
		return null;
	}

}


